package nix.mall.search.service.impl;

import java.util.List;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import nix.mall.common.pojo.NixMallResult;
import nix.mall.common.pojo.SearchItem;
import nix.mall.search.mapper.SearchItemMapper;
import nix.mall.search.service.SearchItemService;

@Service
public class SearchItemServiceImpl implements SearchItemService {

	/*<schema>
	...
	
	<fieldType name="text_ik" class="solr.TextField">
	   <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
	</fieldType>
	
	<field name="item_title" type="text_ik" indexed="true" stored="true"/>
	<field name="item_sell_point" type="text_ik" indexed="true" stored="true"/>
	<field name="item_price"  type="long" indexed="true" stored="true"/>
	<field name="item_image" type="string" indexed="false" stored="true" />
	<field name="item_category_name" type="string" indexed="true" stored="true" />
	<field name="item_desc" type="text_ik" indexed="true" stored="false" />
	
	<field name="item_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/>
	<copyField source="item_title" dest="item_keywords"/>
	<copyField source="item_sell_point" dest="item_keywords"/>
	<copyField source="item_category_name" dest="item_keywords"/>
	<copyField source="item_desc" dest="item_keywords"/>
	
	</schema>*/
	
	@Autowired
	private SearchItemMapper searchItemMapper;
	
	@Autowired
	private SolrServer solrServer;
	
	@Override
	public NixMallResult importItemsToIndex() {
		try {
			// 查询所有商品
			List<SearchItem> list = searchItemMapper.getItemList();
			// 遍历商品数据添加至索引库
			for (SearchItem searchItem : list) {
				// 创建文档对象
				SolrInputDocument document = new SolrInputDocument();	
				// 向文档对象中添加域
				document.addField("id", searchItem.getId());
				document.addField("item_title", searchItem.getTitle());
				document.addField("item_sell_point", searchItem.getSell_Point());
				document.addField("item_price", searchItem.getPrice());
				document.addField("item_image", searchItem.getImage());
				document.addField("item_category_name", searchItem.getCategory_name());
				document.addField("item_desc", searchItem.getItemDesc());
				// 把文档写入索引库
				solrServer.add(document);
			}
			// 提交
			solrServer.commit();		
		} catch (Exception e) {
			return NixMallResult.build(500, "数据导入失败！");
		}
		// 返回结果
		return NixMallResult.ok();
	}	
}
